package com.server.modules.sys.web.statistics;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.server.common.config.Global;
import com.server.common.persistence.Page;
import com.server.common.utils.StringUtils;
import com.server.common.web.BaseController;
import com.server.modules.sys.common.StaticDefine;
import com.server.modules.sys.entity.Office;
import com.server.modules.sys.entity.User;
import com.server.modules.sys.entity.loan.Loan;
import com.server.modules.sys.service.OfficeService;
import com.server.modules.sys.service.StatisticsService;
import com.server.modules.sys.service.SystemService;
import com.server.modules.sys.utils.date.DateUtil;
import com.server.modules.sys.vo.statistics.TimeRangeParam;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "${adminPath}/sys/statistics")
public class StatisticsController extends BaseController {
	@Resource
	private SystemService systemService;
	@Resource
	private OfficeService officeService;
	@Resource
	private StatisticsService statisticsService;
	@RequiresPermissions("sys:statistics:view")
	@RequestMapping(value = {"list", ""})
	public String list(Loan loan, HttpServletRequest request, HttpServletResponse response, Model model) {
		handleParam(model);
		return "modules/sys/statistics/statistics";
	}
	
	@RequiresPermissions("sys:statistics:view")
	@RequestMapping(value = {"customPay"})
	public String customPay(Loan loan, HttpServletRequest request, HttpServletResponse response, Model model) {
		handleParam(model);
		return "modules/sys/statistics/statistics_custompay";
	}
	
	@RequiresPermissions("sys:statistics:view")
	@RequestMapping(value = {"serviceCharge"})
	public String serviceCharge(Loan loan, HttpServletRequest request, HttpServletResponse response, Model model) {
		handleParam(model);
		return "modules/sys/statistics/statistics_service_charge";
	}
	@RequiresPermissions("sys:statistics:view")
	@RequestMapping(value = {"finishLoan"})
	public String finishLoan(Loan loan, HttpServletRequest request, HttpServletResponse response, Model model) {
		handleParam(model);
		return "modules/sys/statistics/statistics_finish_loan";
	}
	@RequiresPermissions("sys:statistics:view")
	@RequestMapping(value = {"refund"})
	public String refund(Loan loan, HttpServletRequest request, HttpServletResponse response, Model model) {
		handleParam(model);
		return "modules/sys/statistics/statistics_refund";
	}
	

	private void handleParam(Model model) {
		List<Office> findList = officeService.findAll();
		for (Office office : findList) {
			if(office.getParentId().equals("0")){
				//默认查全公司数据 查询出公司名称
				model.addAttribute("company", office);
			}
		}
		 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); 
		 //获取当前月第一天：
        Calendar c = Calendar.getInstance();    
        c.add(Calendar.MONTH, 0);
        c.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天 
        String first = format.format(c.getTime());
        model.addAttribute("startDate", first);
        
        //获取当前月最后一天
        Calendar ca = Calendar.getInstance();    
        ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));  
        String last = format.format(ca.getTime());
        model.addAttribute("endDate", last);
        //获取近期六个月
        String[] latelyNMonths = DateUtil.getLatelyNMonths(6);
        model.addAttribute("startMonth", latelyNMonths[0]);
        model.addAttribute("endMonth", latelyNMonths[5]);
        //获取近期四周
        Calendar ca2 = Calendar.getInstance();
        ca2.setFirstDayOfWeek(Calendar.MONDAY);
        int i = ca2.get(Calendar.WEEK_OF_YEAR);
        int year = ca2.get(Calendar.YEAR);
        
        model.addAttribute("endWeekText", year+"年第"+i+"周");
        model.addAttribute("endWeek", ""+year+i);
        model.addAttribute("endWeekDate",DateUtil.DateToString(ca2.getTime(), "yyyy-MM-dd"));
        if(i-3<0){
        	int maxWeek = DateUtil.getMaxWeekNumOfYear(year-1);
        	int startYear=year-1;
        	int startWeek=maxWeek-Math.abs(i-3);
        	 model.addAttribute("startWeekText", startYear+"年第"+startWeek+"周");
             model.addAttribute("startWeek", ""+startYear+startWeek);
             ca2.add(Calendar.WEEK_OF_YEAR, -3);//周减3
             model.addAttribute("startWeekDate",DateUtil.DateToString(ca2.getTime(), "yyyy-MM-dd")  );
        }else{
        	int w=i-3;
        	 model.addAttribute("startWeekText", year+"年第"+w+"周");
             model.addAttribute("startWeek", ""+year+w);
             ca2.add(Calendar.WEEK_OF_YEAR, -3);//周减3
             model.addAttribute("startWeekDate",DateUtil.DateToString(ca2.getTime(), "yyyy-MM-dd")  );
        }
	}
	
	@RequiresPermissions("sys:statistics:view")
	@RequestMapping(value = "/ajaxGetHistogramData")
	@ResponseBody
	public Object ajaxGetHistogramData(User user,TimeRangeParam param, HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
		String statisticsType = param.getStatisticsType();
		switch (statisticsType) {
		case StaticDefine.STATISTICS_TYPE.USERGROWTH:
			return statisticsService.getUserGrowthEchartsData(param);
		case StaticDefine.STATISTICS_TYPE.APPLYCUSTOMPAY:
			return statisticsService.getApplyCustomPayEchartsData(param);
		case StaticDefine.STATISTICS_TYPE.SERVICECHARGE:
			return statisticsService.getServiceChargeEchartsData(param);
		case StaticDefine.STATISTICS_TYPE.FINISHLOAN:
			return statisticsService.getFinishLoanEchartsData(param);
			case StaticDefine.STATISTICS_TYPE.REFUND:
				return statisticsService.getRefundEchartsData(param);
			default:
			break;
		}
		return null;
	}

	@RequiresPermissions("sys:statistics:view")
	@RequestMapping(value = "/userlist")
	public String list(User user, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<User> p=new Page<User>(request, response);
		p.setPageSize(15);
		Page<User> page = systemService.findUser1(p, user);
        model.addAttribute("page", page);
        Office office = user.getOffice();
        model.addAttribute("office", office);
		return "modules/sys/statistics/userList";
	}
	@RequiresPermissions("sys:statistics:view")
	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> treeData(@RequestParam(required=false) String extId, @RequestParam(required=false) String type,
											  @RequestParam(required=false) Long grade, @RequestParam(required=false) Boolean isAll, HttpServletResponse response) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		List<Office> list = officeService.findList(isAll);
		for (int i=0; i<list.size(); i++){
			Office e = list.get(i);
			if ((StringUtils.isBlank(extId) || (extId!=null && !extId.equals(e.getId()) && e.getParentIds().indexOf(","+extId+",")==-1))
					&& (type == null || (type != null && (type.equals("1") ? type.equals(e.getType()) : true)))
					&& (grade == null || (grade != null && Integer.parseInt(e.getGrade()) <= grade.intValue()))
					&& Global.YES.equals(e.getUseable())){
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", e.getId());
				map.put("pId", e.getParentId());
				map.put("pIds", e.getParentIds());
				map.put("name", e.getName());
				if (type != null && "3".equals(type)){
					map.put("isParent", true);
				}
				mapList.add(map);
			}
		}
		return mapList;
	}

	

}